package com.sixuan.rabbitmqconsumer.workmode.routing;

import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * RabbitMq工作模式：Routing（路由模式）
 * 1.生命一个交换机，并指定该交换机是DIRECT模式（即routing模式）
 * 2.一个交换机绑定多个队列，每个队列设置自己的routingKey，且一个队列可以设置多个routingKey。
 * 3.每个消费则监听自己的队列
 * 4.生产将消息发给指定的交换机，发送的时候需要指定routingKey，交换机来发送给指定了该routingKey的所有队列
 * Routing模式和Publish/Subscribe模式的区别：
 * 1.Publish/Subscribe模式不需要指定RoutingKey，消息会发送给与该交换机绑定的所有队列。
 * 2.当两个队列RoutingKey相同时，此时Routing模式的效果与Publish/Subscribe模式一致
 * 3.即Routing模式比Publish/Subscribe模式更强大。
 * Created by LENOVO on 2020-7-8 17:18
 *
 * @author LENOVO
 */
public class SmsConsumer1 {

    private static final String rabbitMqHost = "47.97.195.191";
    private static final int rabbitMqPort = 5672;
    private static final String username = "guest";
    private static final String password = "guest";

    private static final String SMS_QUEUE_INFORMATION = "sms_queue_information";
    private static final String EXCHANGE_ROUTING = "exchange_routing";
    private static final String SMS_ROUTING_INFORMATION = "sms_routing_information";

    public static void main(String[] args) throws Exception {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(rabbitMqHost);
        connectionFactory.setPort(rabbitMqPort);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        connectionFactory.setVirtualHost("/");
        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();
        //声明交换机
        channel.exchangeDeclare(EXCHANGE_ROUTING, BuiltinExchangeType.DIRECT);
        //声明队列
        channel.queueDeclare(SMS_QUEUE_INFORMATION, true, false, false, null);
        //将队列绑定到交换机上
        channel.queueBind(SMS_QUEUE_INFORMATION, EXCHANGE_ROUTING, SMS_ROUTING_INFORMATION);
        //为了测试Routing模式比Publish/Subscribe模式更强大
        channel.queueBind(SMS_QUEUE_INFORMATION, EXCHANGE_ROUTING, "RoutingMode");
        //接收到消息后的执行方法
        DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //交换机
                String exchange = envelope.getExchange();
                long deliveryTag = envelope.getDeliveryTag();
                String message = new String(body, "utf-8");
                System.out.println("Received from provider : " + message);
            }
        };
        //监听消息basicConsume
        channel.basicConsume(SMS_QUEUE_INFORMATION, true, defaultConsumer);
    }
}
